#coding=utf-8
from uliweb.form import *
from uliweb.i18n import ugettext_lazy as _

class ChangePasswordForm1(Form):
    form_buttons = Submit(value=_('Save'), _class="button")

    oldpassword = PasswordField(label=_('Old Password'), required=True)
    password = PasswordField(label=_('Password'), required=True)
    password1 = PasswordField(label=_('Password again'), required=True)

    def validate_oldpassword(self, data):
        from uliweb import request
            
        if not request.user.check_password(data):
            return '密码不正确。'

class ChangePasswordForm2(Form):
    form_buttons = Submit(value=_('Save'), _class="button")

    username = UnicodeField(label='用户姓名', required=True)
    oldpassword = PasswordField(label=_('Old Password'), required=True)
    password = PasswordField(label=_('Password'), required=True)
    password1 = PasswordField(label=_('Password again'), required=True)
    
    def form_validate(self, all_data):
        from uliweb.orm import get_model
        error = {}
        
        User = get_model('user')
        user = User.get(User.c.username == all_data.get('username'))
        if not user:
            error['username'] = '用户名不存在'
        else:
            if not user.check_password(all_data.get('oldpassword')):
                error['oldpassword'] = '密码不正确。'
        
            if all_data.password != all_data.password1:
                error['password1'] = "两次输入的密码不一致"
        return error
    
class UserForm(Form):
    def validate_username(self, data):
        from uliweb.orm import get_model
                 
        User = get_model('user')
        user = User.get(User.c.username == data)
        if (not self.user and user) or (user and self.user and self.user.id != user.id):
            return '用户名已存在'
    
class EditUserForm(UserForm):
    def form_validate(self, all_data):
        error = {}
        
        if all_data['department'] == '1':  #如果部门为条线，则tx字段不能为空
            if not all_data['tx']:
                error['tx'] = "请选择所属条线"
        elif all_data['department'] == '2':    #如果部门为开发中心，则kfzx字段不能为空
            if not all_data['kfzx']:
                error['kfzx'] = "请选择所属开发中心"
        if all_data['kfzx'] and not all_data['department']:
            error['department'] = "请选择所属机构为开发中心"
        if all_data['tx'] and not all_data['department']:
            error['department'] = "请选择所属机构为条线"
            
        return error
     
